<template>
  <div class="main commodity-mfreight-edit">
    <div class="main-title">
      <h4>{{ this.id ? '编辑配送模板':'新建配送模板' }}</h4>
      <div class="btn-box">
        <el-button
          class="filter-item"
          type="success"
          size="small"
          @click="save"
        >保存</el-button>
        <el-button
          class="filter-item"
          type="danger"
          size="small"
          @click="updateStatus"
        >返回</el-button>
      </div>
    </div>
    <el-card class="box-card">
      <h4 class="mfreight-title">模板基本信息</h4>
      <el-form
        ref="formBase"
        :model="formData"
        :rules="rulesBase"
        size="medium"
        label-width="150px"
      >
        <el-form-item label="模板名称:" prop="name">
          <el-input v-model="formData.name" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="设置为默认模板:" prop="defaulted">
          <el-switch v-model="formData.defaulted" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
        <el-form-item label="计算类型:" prop="calcuType">
          <el-radio-group v-model="formData.calcuType">
            <el-radio :key="1" :label="1" :value="1" @change="radioEvent('weight')">重量</el-radio>
            <el-radio :key="3" :label="3" :value="3" @change="radioEvent('num')">件数</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择计费方式:" prop="feeType">
          <el-radio-group v-model="formData.feeType">
            <el-radio :key="1" :label="1" :value="1" @change="changeFeeType()">普通计费</el-radio>
            <el-radio :key="2" :label="2" :value="2" :disabled="formData.calcuType===1" @change="changeFeeType()">区间计费</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <h4 class="mfreight-title">模板详情</h4>
      <div class="mfreight-area">
        <!-- <el-form
          :model="formData"
          :rules="rulesBase"
          size="medium"
          ref="formBase"
          label-width="150px"
          class
        > -->
        <!-- <el-form-item label="是否全国包邮:">
            <el-radio-group v-model="formData.isBuy">
              <el-radio label="包邮" :key="1" :value="1"></el-radio>
              <el-radio label="不包邮" :key="2" :value="2"></el-radio>
            </el-radio-group>
          </el-form-item> -->

        <!-- <el-form-item> -->
        <div class="area-wrapper area-title-wrapper">
          <h4 class="title-free">配送地区</h4>
          <el-button type="success" size="small" icon="el-icon-plus" class="filter-item area-btn" @click="chooseJump('add')">添加</el-button>
          <el-button type="success" size="small" icon="el-icon-plus" class="filter-item area-btn" @click="importButton">导入</el-button>
          <el-dialog :visible.sync="importMFreightDialog" :before-close="cancelImportMFreight" width="40%">
            <el-upload
              ref="upload"
              class="upload-demo"
              accept="xlsx"
              :multiple="false"
              :action="upladUrl"
              :before-upload="fileCheck"
              :on-success="handleExceed"
              :on-remove="handleRemove"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">导入运费模板</el-button>
              <!-- <div slot="tip" class="el-upload__tip">文件名称+导入成功</div> -->
            </el-upload>
            <span slot="footer">
              <el-button type="primary" @click="confirmImportMFreight">确 定</el-button>
              <el-button type="danger" @click="cancelImportMFreight">取消</el-button>
            </span>
          </el-dialog>
        </div>
        <!-- 第二个版本需要 start-->
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="给我一点时间"
          :header-cell-style="{background: '#eee'}"
          style="width: 90%; margin-bottom: 20px"
          border
          highlight-current-row
        >

          <!--计重-->
          <template v-if="formData.calcuType===1" style="float: left">
            <el-table-column :key="Math.random()" align="center" label="首重(kg)" prop="weightFirst" width="110px">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.startUnit"
                  disabled
                  @keyup.native="floatRule(scope.row.startUnit, 'startUnit', scope.$index)"
                  @blur="floatFixed(scope.row.startUnit, 'startUnit', scope.$index, 1)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" align="center" label="首重运费(元)" prop="weightFirstPrice" width="110px">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.price"
                  disabled
                  @keyup.native="floatRule(scope.row.price, 'price', scope.$index)"
                  @blur="floatFixed(scope.row.price, 'price', scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" align="center" label="续重(kg)" prop="weightContinue" width="110px">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.continuedUnit"
                  disabled
                  @keyup.native="floatRule(scope.row.continuedUnit, 'continuedUnit', scope.$index)"
                  @blur="floatFixed(scope.row.continuedUnit, 'continuedUnit', scope.$index, 1)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" align="center" label="续重运费(元)" prop="weightContinuePrice" width="110px">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.continuedPrice"
                  disabled
                  @keyup.native="floatRule(scope.row.continuedPrice, 'continuedPrice', scope.$index)"
                  @blur="floatFixed(scope.row.continuedPrice, 'continuedPrice', scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
          </template>
          <!--计件-->
          <template v-if="formData.calcuType===3" style="float: left">
            <template v-if="formData.feeType===2">
              <el-table-column :key="Math.random()" align="center" label="件数区间" prop="weightFirst" width="220px">
                <template slot-scope="scope">
                  <el-row v-for="(item, index) in scope.row.freightIntervalDetails" :key="index">
                    <el-col :span="11">
                      <el-input v-model="item.intervalStart" disabled></el-input>
                    </el-col>
                    <el-col :span="2">
                      <span style="vertical-align: sub;">-</span>
                    </el-col>
                    <el-col :span="11">
                      <el-input v-model="item.intervalEnd" disabled @input="item.intervalEnd=$event.replace(/[^\d]/g,'')"></el-input>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="首件件数" prop="countFirst" width="110px">
                <template slot-scope="scope">
                  <el-input v-for="(item, index) in scope.row.freightIntervalDetails" :key="index" v-model="item.startUnit" disabled @keyup.native="initRule(item.startUnit, 'startUnit', scope.$index, 1)"></el-input>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="首件运费(元)" prop="countFirstPrice" width="110px">
                <template slot-scope="scope">
                  <el-input
                    v-for="(item, index) in scope.row.freightIntervalDetails"
                    :key="index"
                    v-model="item.price"
                    disabled
                    @keyup.native="floatRule(item.price, 'price', scope.$index)"
                    @blur="floatFixed(item.price, 'price', scope.$index)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="续件件数" prop="countContinue" width="110px">
                <template slot-scope="scope">
                  <el-input v-for="(item, index) in scope.row.freightIntervalDetails" :key="index" v-model="item.continuedUnit" disabled @keyup.native="initRule(item.continuedUnit, 'continuedUnit', scope.$index, 1)"></el-input>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="续件运费(元)" prop="countContinuePrice" width="110px">
                <template slot-scope="scope">
                  <el-input
                    v-for="(item, index) in scope.row.freightIntervalDetails"
                    :key="index"
                    v-model="item.continuedPrice"
                    disabled
                    @keyup.native="floatRule(item.continuedPrice, 'continuedPrice', scope.$index)"
                    @blur="floatFixed(item.continuedPrice, 'continuedPrice', scope.$index)"
                  ></el-input>
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column :key="Math.random()" align="center" label="首件件数" prop="countFirst" width="110px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.startUnit" disabled @keyup.native="initRule(scope.row.startUnit, 'startUnit', scope.$index, 1)"></el-input>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="首件运费(元)" prop="countFirstPrice" width="110px">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.price"
                    disabled
                    @keyup.native="floatRule(scope.row.price, 'price', scope.$index)"
                    @blur="floatFixed(scope.row.price, 'price', scope.$index)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="续件件数" prop="countContinue" width="110px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.continuedUnit" disabled @keyup.native="initRule(scope.row.continuedUnit, 'continuedUnit', scope.$index, 1)"></el-input>
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" align="center" label="续件运费(元)" prop="countContinuePrice" width="110px">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.continuedPrice"
                    disabled
                    @keyup.native="floatRule(scope.row.continuedPrice, 'continuedPrice', scope.$index)"
                    @blur="floatFixed(scope.row.continuedPrice, 'continuedPrice', scope.$index)"
                  ></el-input>
                </template>
              </el-table-column>
            </template>
          </template>
          <template style="float: left">
            <el-table-column :key="Math.random()" align="center" label="地区" prop="area">
              <template slot-scope="scope">
                <div class="area-wrapper">
                  <p class="area-list">
                    {{ scope.row.string }}
                  </p>
                  <div class="area-edit">
                    <el-button type="text" @click="chooseJump('edit', scope.$index)">编辑</el-button>
                    <el-button type="text" @click="deleteRule(scope.$index)">删除</el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
          </template>
        </el-table>
        <!-- 第二个版本需要 end-->

        <!--<el-table-->
        <!--:data="list"-->
        <!--v-loading="listLoading"-->
        <!--style="width: 90%;margin-bottom: 20px"-->
        <!--element-loading-text="给我一点时间"-->
        <!--border-->
        <!--highlight-current-row-->
        <!--:header-cell-style="{background: '#f1f1f1'}"-->
        <!--&gt;-->
        <!--<el-table-column align="center" label="地区">-->
        <!--<template slot-scope="scope">-->
        <!--<p style="text-align: left">{{scope.row.area}}</p>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <!--</el-table>-->

        <div class="area-wrapper area-title-wrapper">
          <h4 class="title-free">不配送地区</h4>
          <!--<el-button type="success" size="mini"  icon="el-icon-plus" class="filter-item area-btn" @click="chooseJump">选择地区</el-button>-->
        </div>
        <el-table
          v-loading="listLoading"
          :data="unlist"
          style="width: 90%;margin-bottom: 20px"
          element-loading-text="给我一点时间"
          border
          highlight-current-row
          :header-cell-style="{background: '#f1f1f1'}"
        >
          <el-table-column :key="Math.random()" align="center" label="地区">
            <template slot-scope="scope">
              <p style="text-align: left">{{ scope.row.area }}</p>
            </template>
          </el-table-column>
        </el-table>
        <!-- </el-form-item> -->
        <!-- </el-form> -->
      </div>
    </el-card>

    <el-dialog
      title=""
      :visible.sync="centerDialogVisible2"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="conf-wrapper">
        <div v-if="formData.defaulted" class="tip">确定使用该模板为默认的运费模板？</div>
        <div v-else class="tip">确认保存？</div>
      </div>
      <div slot="footer" class>
        <el-button type="success" @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="sureSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTemplateById, addAndUpdate } from '@/api/freight'
import { regexp } from '@/utils/tools'

export default {
  props: {
    id: { default: '' }
  },
  data() {
    return {
      btnLoading: false,
      listLoading: false,
      formData: {
        name: '',
        defaulted: false,
        calcuType: null, // 计算类型
        feeType: null, // 计费方式
        details: [
        //   {
        //   continuedPrice: 0,
        //   continuedUnit: 0,
        //   deliveryAddrCode: 'string',
        //   deliveryAddrName: 'string',
        //   freightWay: 0,
        //   price: 0,
        //   startUnit: 0
        // }
        ],
        pinkage: 0,
        unsupported: ''
      },

      rulesBase: {
        name: [{ required: true, message: '不能为空', trigger: 'change' }],
        defaulted: [{ required: true, message: '不能为空' }],
        calcuType: [{ required: true, message: '请选择计算方式' }],
        feeType: [{ required: true, message: '请选择计费方式' }]
      },
      // 已添加规则区域
      chosedArea: [],
      // 不配送地区
      unsupported: [
        // {
        //   name: "西藏，云南",
        //   value: ""
        // }
      ],
      // 配送地区
      supported: [],
      unlist: [],
      list: [],
      centerDialogVisible2: false, // 设置模板
      provinceData: [],
      calcuCache: {
        weight: [],
        num: []
      },
      importMFreightDialog: false,
      fileList: [],
      remoteUrl: '', // 导入运费模板的URL
      fileArray:[],
      isConfirm:false
    }
  },
  created() {
    this.getAllArea()
  },
  methods: {
    changeFeeType(val) {
      if (this.formData.calcuType === 1) { // 重量
        this.list.map((item, index) => {
          item.startUnit = '1.00'
          item.price = '0.00'
          item.continuedUnit = '1.00'
          item.continuedPrice = '0.00'
        })
      } else {
        this.list.map((item, index) => { // 件数
          item.startUnit = '1'
          item.price = '0.00'
          item.continuedUnit = '1'
          item.continuedPrice = '0.00'
          if (this.formData.feeType === 2) {
            item.freightIntervalDetails = [{
              intervalStart: 1,
              intervalEnd: null,
              startUnit: this.formData.calcuType === 1 ? '1.00' : 1,
              price: '0.00',
              continuedUnit: this.formData.calcuType === 1 ? '1.00' : 1,
              continuedPrice: '0.00'
            }]
          }
        })
      }
    },
    // 改变计算方式
    radioEvent(val) {
      this.$set(this.formData, 'feeType', 1)
      switch (val) {
        case 'num':
          // 把 重量保存下来 然后置空数据
          this.calcuCache.weight = []
          this.list.map((item, index) => {
            this.calcuCache.weight.push({
              startUnit: item.startUnit,
              price: item.price,
              continuedUnit: item.continuedUnit,
              continuedPrice: item.continuedPrice
            })
          })
          // 如果有保存 数据
          if (this.calcuCache.num.length) {
            this.list.map((item, index) => {
              item.startUnit = this.calcuCache.num[index].startUnit,
              item.price = this.calcuCache.num[index].price,
              item.continuedUnit = this.calcuCache.num[index].continuedUnit,
              item.continuedPrice = this.calcuCache.num[index].continuedPrice
            })
          } else {
            this.list.map((item, index) => {
              item.startUnit = '1'
              item.price = '0.00'
              item.continuedUnit = '1'
              item.continuedPrice = '0.00'
            })
          }
          break
        case 'weight':
          this.calcuCache.num = []
          this.list.map(item => {
            this.calcuCache.num.push({
              startUnit: item.startUnit,
              price: item.price,
              continuedUnit: item.continuedUnit,
              continuedPrice: item.continuedPrice,
              freightIntervalDetails: item.freightIntervalDetails ? item.freightIntervalDetails : []
            })
          })
          if (this.calcuCache.weight.length) {
            this.list.map((item, index) => {
              item.startUnit = this.calcuCache.weight[index].startUnit,
              item.price = this.calcuCache.weight[index].price,
              item.continuedUnit = this.calcuCache.weight[index].continuedUnit,
              item.continuedPrice = this.calcuCache.weight[index].continuedPrice
            })
          } else {
            this.list.map((item, index) => {
              item.startUnit = '1.00'
              item.price = '0.00'
              item.continuedUnit = '1.00'
              item.continuedPrice = '0.00'
            })
          }
          break
        default: ''
      }
    },

    initRule(value, key, index, must) {
      if (typeof value !== 'string') {
        value = JSON.stringify(value)
      }
      value = value.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
      if (must && value * 1 === 0) {
        value = '1'
      }
      this.list[index][key] = value
    },
    floatFixed(value, key, index, must) {
      value = Number(value).toFixed(2)
      if (must && value * 1 === 0) {
        value = '1.00'
      }
      this.list[index][key] = value
    },
    floatRule(value, key, index) {
      if (typeof value !== 'string') {
        value = JSON.stringify(value)
      }
      value = value.replace(/[^\d\.]/g, '')
      this.list[index][key] = value
    },

    // 获取地区数据
    getAllArea() {
      const dataList = require('../../../../../static/BSNLAddress.json')
      this.provinceData = dataList.filter((item) => item.parent === '0')

      // 初始化，所有地区先放在不配送范围
      this.unsupported = JSON.parse(JSON.stringify(this.provinceData))
      this.getEditData()
    },
    // 获取编辑数据
    getEditData() {
      const detailData = sessionStorage.getItem('shippingData')
      if (this.id) {
        getTemplateById(this.id).then(res => {
          if (res.code == 0) {
            this.commonData(res)
          }
        }).catch(err => {
          this.formData.name = ''
          this.formData.defaulted = false
          this.formData.details = []
          this.formData.pinkage = false
          this.formData.unsupported = ''
          this.setArea()
        })
      } else if (detailData && !this.id) {
        this.formData = JSON.parse(detailData)
        const unsupported = this.formData.unsupported ? this.formData.unsupported.split(',') : []
        this.unsupported = []
        unsupported.forEach(item => {
          this.provinceData.forEach(sitem => {
            if (sitem.name.indexOf(item) > -1) {
              this.unsupported.push({
                ...sitem,
                realname: sitem.name
              })
            }
          })
        })

        // 初始化取到的配置
        const listSplit = []
        // 判断数据是否为1.0版本的, line不为空则为2.0， 空则为1.0
        if (this.formData.details[0].line !== null) {
          this.formData.details.map(item => {
            item.name = item.deliveryAddrName
            item.value = item.deliveryAddrCode
            item.realname = item.deliveryAddrName
            if (!listSplit[item.line]) {
              listSplit[item.line] = {}
              if (listSplit[item.line].ruleArea) {
                console.log('none')
              } else {
                const index = item.line
                listSplit[item.line].ruleArea = []
                const arr = listSplit[index].ruleArea
                delete item['line']
                arr.push(item)
              }
            } else {
              const index = item.line
              delete item['line']
              listSplit[index].ruleArea.push(item)
            }
          })
          listSplit.forEach(item => {
            let str = ''
            item.ruleArea.forEach(sitem => {
              str += (sitem.deliveryAddrName) + ','
              this.chosedArea.push(sitem)
            })
            str = str.slice(0, str.length - 1)
            if (this.formData.calcuType === 1) {
              item.startUnit = item.ruleArea[0].startUnit.toFixed(2)
              item.price = item.ruleArea[0].price.toFixed(2)
              item.continuedUnit = item.ruleArea[0].continuedUnit.toFixed(2)
              item.continuedPrice = item.ruleArea[0].continuedPrice.toFixed(2)
              item.freightIntervalDetails = item.ruleArea[0].freightIntervalDetails ? item.ruleArea[0].freightIntervalDetails : []
            } else if (this.formData.calcuType === 3) {
              item.startUnit = item.ruleArea[0].startUnit
              item.price = item.ruleArea[0].price.toFixed(2)
              item.continuedUnit = item.ruleArea[0].continuedUnit
              item.continuedPrice = item.ruleArea[0].continuedPrice.toFixed(2)
              item.freightIntervalDetails = item.ruleArea[0].freightIntervalDetails ? item.ruleArea[0].freightIntervalDetails : []
            }
            item.string = str
          })
        } else {
          // 1.0 版本处理
          let str = ''
          listSplit[0] = {}
          listSplit[0].ruleArea = []

          this.formData.details.forEach(sitem => {
            str += sitem.deliveryAddrName + ','
            sitem.name = sitem.deliveryAddrName
            sitem.value = sitem.deliveryAddrCode
            sitem.realname = sitem.deliveryAddrName
            this.chosedArea.push(sitem)
            listSplit[0].ruleArea.push(sitem)
          })
          str = str.slice(0, str.length - 1)

          listSplit[0].startUnit = 0
          listSplit[0].price = 0
          listSplit[0].continuedUnit = 0
          listSplit[0].continuedPrice = 0
          listSplit[0].string = str
        }

        this.list = listSplit

        this.setArea()
      } else {
        this.setArea()
      }
    },
    // 设置配送地区
    setArea() {
      // 列出已经选中的区域
      const chosedIndex = []
      this.provinceData.forEach((item, index) => {
        this.chosedArea.forEach(sitem => {
          if (item.name.indexOf(sitem.name) >= 0) {
            chosedIndex.push(index)
          }
        })
      })
      const uns = []
      this.provinceData.map((item, index) => {
        if (chosedIndex.indexOf(index) < 0) {
          uns.push(this.provinceData[index])
        }
      })
      this.unsupported = uns
      // 构造配送地区

      // let unsupportedIndex = []
      // // 统计不配送区域的序号
      // this.provinceData.forEach((item, index) => {
      //   this.unsupported.forEach(sitem => {
      //     if (item.name.indexOf(sitem.name) > -1) {
      //      unsupportedIndex.push(index)
      //     }
      //   })
      // })
      // this.supported = []
      // this.provinceData.forEach((item, index) => {
      //     if (unsupportedIndex.indexOf(index) == -1) {
      //       this.supported.push(item)
      //     }
      //  })

      // let areaList = []
      // this.supported.forEach(item => {
      //   areaList.push(item.name)
      // })
      // this.list = []
      // if (areaList.length > 0) {
      //   this.list.push({
      //     area: areaList.join(',')
      //   })
      // }
      // 构造不配送地区
      const areaunList = []
      this.unsupported.forEach(item => {
        areaunList.push(item.realname || item.name)
      })
      this.unlist = []
      if (areaunList.length > 0) {
        this.unlist.push({
          area: areaunList.join(',')
        })
      }
    },
    // 删除配送规则
    deleteRule(index) {
      const removeIndex = []
      const arr = this.list[index].ruleArea
      this.chosedArea.forEach((item, index) => {
        arr.forEach(sitem => {
          if (item.name.indexOf(sitem.name) >= 0) {
            removeIndex.push(index)
          }
        })
      })
      const uns = []
      this.chosedArea.map((item, index) => {
        if (removeIndex.indexOf(index) < 0) {
          uns.push(this.chosedArea[index])
        }
      })
      this.chosedArea = uns
      this.list.splice(index, 1)
      this.setArea()
    },
    commonData(res) {
      this.formData = res.data
      if (res.data.calcuType) {
        this.$set(this.formData, 'calcuType', res.data.calcuType)
      } else {
        this.$set(this.formData, 'calcuType', null)
      }
      if (res.data.feeType) {
        this.$set(this.formData, 'feeType', res.data.feeType)
      } else {
        this.$set(this.formData, 'feeType', null)
      }
      const unsupported = this.formData.unsupported ? this.formData.unsupported.split(',') : []
      this.unsupported = []
      unsupported.forEach(item => {
        this.provinceData.forEach(sitem => {
          if (sitem.name.indexOf(item) > -1) {
            this.unsupported.push({
              ...sitem,
              realname: sitem.name
            })
          }
        })
      })

      // 初始化取到的配置
      const listSplit = []

      // 判断数据是否为1.0版本的, line不为空则为2.0， 空则为1.0
      if (res.data.details[0].line !== null) {
        res.data.details.map(item => {
          item.name = item.deliveryAddrName
          item.value = item.deliveryAddrCode
          item.realname = item.deliveryAddrName
          if (!listSplit[item.line]) {
            listSplit[item.line] = {}
            if (listSplit[item.line].ruleArea) {
              console.log('none')
            } else {
              const index = item.line
              listSplit[item.line].ruleArea = []
              const arr = listSplit[index].ruleArea
              delete item['line']
              arr.push(item)
            }
          } else {
            const index = item.line
            delete item['line']
            listSplit[index].ruleArea.push(item)
          }
        })
        listSplit.forEach(item => {
          let str = ''
          item.ruleArea.forEach(sitem => {
            str += (sitem.deliveryAddrName) + ','
            this.chosedArea.push(sitem)
          })
          str = str.slice(0, str.length - 1)
          if (this.formData.calcuType === 1) {
            item.startUnit = item.ruleArea[0].startUnit.toFixed(2)
            item.price = item.ruleArea[0].price.toFixed(2)
            item.continuedUnit = item.ruleArea[0].continuedUnit.toFixed(2)
            item.continuedPrice = item.ruleArea[0].continuedPrice.toFixed(2)
            item.freightIntervalDetails = item.ruleArea[0].freightIntervalDetails ? item.ruleArea[0].freightIntervalDetails : []
          } else if (this.formData.calcuType === 3) {
            item.startUnit = item.ruleArea[0].startUnit
            item.price = item.ruleArea[0].price.toFixed(2)
            item.continuedUnit = item.ruleArea[0].continuedUnit
            item.continuedPrice = item.ruleArea[0].continuedPrice.toFixed(2)
            item.freightIntervalDetails = item.ruleArea[0].freightIntervalDetails ? item.ruleArea[0].freightIntervalDetails : []
          }
          item.string = str
        })
      } else {
        // 1.0 版本处理
        let str = ''
        listSplit[0] = {}
        listSplit[0].ruleArea = []

        res.data.details.forEach(sitem => {
          str += sitem.deliveryAddrName + ','
          sitem.name = sitem.deliveryAddrName
          sitem.value = sitem.deliveryAddrCode
          sitem.realname = sitem.deliveryAddrName
          this.chosedArea.push(sitem)
          listSplit[0].ruleArea.push(sitem)
        })
        str = str.slice(0, str.length - 1)

        listSplit[0].startUnit = 0
        listSplit[0].price = 0
        listSplit[0].continuedUnit = 0
        listSplit[0].continuedPrice = 0
        listSplit[0].string = str
      }
      this.list = listSplit
      this.setArea()
    },
    // 导入按钮
    importButton() {
      if (!this.formData.calcuType) {
        this.$message({
          message: '请先选择计算类型',
          type: 'error'
        })
        return
      }
      if (this.formData.feeType != 2) {
        this.$message({
          message: '导入功能请选择区间计费',
          type: 'error'
        })
        return
      }
      this.importMFreightDialog = true
    },
    fileCheck(file) {
      if (file.name.indexOf('xlsx') <= -1) {
        this.$message('只能上传xlsx格式文件')
        return false
      }
    },
    
    handleExceed(res, file, fileList) {
      this.fileArray.push(fileList)
      this.fileList = fileList
      if (this.fileList.length > 1) {
        this.fileList.splice(0, 1)
      }
      this.remoteUrl = res.filePath
    },
    handleRemove() {
      this.remoteUrl = ''
    },
    cancelImportMFreight() {
      this.fileList = this.isConfirm ? this.fileArray[0] :[]
      this.importMFreightDialog = false
    },
    confirmImportMFreight() {
      if (this.remoteUrl === '') {
        this.$message.warning('请先导入运费模板')
        return false
      }
      this.request({
        url: '/v1/freight/template/excel/import',
        method: 'post',
        data: {
          calcuType: this.formData.calcuType,
          feeType: this.formData.feeType,
          remoteUrl: this.remoteUrl
        }
      }).then(res => {
        if (res.code == 0) {
          this.isConfirm = true
          this.fileArray = []
          this.fileArray.push(this.fileList)
          const deliveryAddrNames = []
          const provinceArray = []
          const changeDetails = []
          res.data.details.forEach((item) => {
            deliveryAddrNames.push(item.deliveryAddrName)
            this.provinceData.forEach(sitem => {
              if (sitem.name.indexOf(item.deliveryAddrName) >= 0) {
                item = {
                  continuedPrice: 0,
                  continuedUnit: 1,
                  deliveryAddrCode: sitem.value,
                  deliveryAddrName: item.deliveryAddrName,
                  freightIntervalDetails: item.freightIntervalDetails,
                  freightWay: this.formData.calcuType,
                  line: item.line,
                  price: 0,
                  startUnit: 1
                }
                changeDetails.push(item)
              }
            })
          })
          this.provinceData.forEach(sitem => {
            provinceArray.push(sitem.name)
          })
          // 不配送区域
          deliveryAddrNames.forEach((deliveryItem) => {
            provinceArray.filter((provinceItem, index) => {
              if (provinceItem.indexOf(deliveryItem) != -1) {
                provinceArray.splice(index, 1)
              }
            })
          })
          res.data = {
            ...this.formData,
            details: changeDetails,
            unsupported: provinceArray.join(',')
          }
          this.chosedArea = []
          this.unsupported = []
          this.unlist = []
          this.commonData(res)
          this.importMFreightDialog = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      }).catch(err => {
        this.formData.name = ''
        this.formData.defaulted = false
        this.formData.details = []
        this.formData.pinkage = false
        this.formData.unsupported = ''
        this.setArea()
      })
    },
    // 选择地区
    chooseJump(type, index) {
      if (!this.formData.calcuType) {
        this.$message({
          message: '请先选择计算类型',
          type: 'error'
        })
        return
      }
      if (!this.formData.feeType) {
        this.$message({
          message: '请先选择计费方式',
          type: 'error'
        })
        return
      }
      const disChose = this.chosedArea
      switch (type) {
        case 'add':
          // 返回被选中的省份
          this.areaChoose({ feeType: this.formData.feeType, calcuType: this.formData.calcuType, tableList: [{
            intervalStart: 1,
            intervalEnd: null,
            startUnit: this.formData.calcuType === 1 ? '1.00' : 1,
            price: '0.00',
            continuedUnit: this.formData.calcuType === 1 ? '1.00' : 1,
            continuedPrice: '0.00'
          }] }, [], disChose).then(val => {
            let str = ''
            // 初始化
            val.result.forEach(item => {
              str += (item.name || item.realname) + ','
              this.chosedArea.push(item)
            })
            if (str.length) {
              str = str.slice(0, str.length - 1)
              if (this.formData.calcuType === 3 && this.formData.feeType === 2) {
                this.list.push({
                  ruleArea: val.result,
                  string: str,
                  startUnit: '1.00',
                  price: '0.00',
                  continuedUnit: '1.00',
                  continuedPrice: '0.00',
                  freightIntervalDetails: val.tableList
                })
              } else {
                this.list.push({
                  ruleArea: val.result,
                  string: str,
                  startUnit: val.tableList[0].startUnit,
                  price: val.tableList[0].price,
                  continuedUnit: val.tableList[0].continuedUnit,
                  continuedPrice: val.tableList[0].continuedPrice
                })
              }
            }
            this.setArea()
          })
          break
        case 'edit':
          // 把要编辑的内容从不可编辑数组解放出来
          const selected = this.list[index].ruleArea
          this.areaChoose({ feeType: this.formData.feeType, calcuType: this.formData.calcuType, tableList: this.formData.calcuType === 3 && this.formData.feeType === 2 ? this.list[index].freightIntervalDetails : [this.list[index]] }, selected, disChose).then(val => {
            // 先把选中列的内容从choseArea 全部删除
            const removeIndex = []
            const arr = this.list[index].ruleArea
            this.chosedArea.forEach((item, index) => {
              arr.forEach(sitem => {
                if (item.name.indexOf(sitem.name) >= 0) {
                  removeIndex.push(index)
                }
              })
            })
            const uns = []
            this.chosedArea.map((item, index) => {
              if (removeIndex.indexOf(index) < 0) {
                uns.push(this.chosedArea[index])
              }
            })
            this.chosedArea = uns

            // 再把重新选好的添加进choseArea, 同时添加进对应的行
            let str = ''
            this.list[index].ruleArea = []
            val.result.forEach(item => {
              str += (item.name || item.realname) + ','
              this.chosedArea.push(item)
              this.list[index].ruleArea.push(item)
            })
            if (str.length) {
              str = str.slice(0, str.length - 1)
              this.list[index].string = str
            }
            this.setArea()
          })
          break

        default: ''
      }
    },

    // 新增或编辑
    save() {
      this.$refs['formBase'].validate(valid => {
        let ifContinue = true
        this.list.forEach((item, index) => {
          const startU = Number(item.startUnit)
          const continuedU = Number(item.continuedUnit)
          if (startU <= 0 || continuedU <= 0) {
            this.$message({
              message: '首单位（件、kg）和续单位（件、kg）不能为0',
              type: 'error'
            })
            ifContinue = false
          }
          if (this.formData.feeType === 2 && this.formData.calcuType === 3 && item.freightIntervalDetails.length > 0 && (!item.freightIntervalDetails[0].intervalStart || !item.freightIntervalDetails[0].intervalEnd)) {
            this.$message({
              message: '件数区间必填',
              type: 'error'
            })
            ifContinue = false
          }
        })
        if (valid && ifContinue) {
          this.formData.unsupported = ''
          if (this.unlist.length > 0) {
            this.formData.unsupported = this.unlist[0].area
          }
          // 写入数据
          // this.list.map(item => {
          //   item.ruleArea.map(sitem => {
          //     sitem.startUnit = item.startUnit
          //     sitem.price = item.price
          //     sitem.continuedUnit = item.continuedUnit
          //     sitem.continuedPrice = item.continuedPrice
          //     return sitem
          //   })
          //   return item
          // })
          this.formData.details = []
          this.list.map((item, index) => {
            if (this.formData.calcuType === 3 && this.formData.feeType === 2) {
              item.ruleArea.map(sitem => {
                sitem.startUnit = 1
                sitem.price = 0
                sitem.continuedUnit = 1
                sitem.continuedPrice = 0
                sitem.freightWay = this.formData.calcuType
                sitem.deliveryAddrCode = sitem.value
                sitem.deliveryAddrName = sitem.realname
                sitem.line = index
                sitem.freightIntervalDetails = item.freightIntervalDetails
                this.formData.details.push(sitem)
              })
            } else {
              item.ruleArea.map(sitem => {
                sitem.startUnit = Number(item.startUnit)
                sitem.price = Number(item.price)
                sitem.continuedUnit = Number(item.continuedUnit)
                sitem.continuedPrice = Number(item.continuedPrice)
                sitem.freightWay = this.formData.calcuType
                sitem.deliveryAddrCode = sitem.value
                sitem.deliveryAddrName = sitem.realname
                sitem.line = index
                sitem.freightIntervalDetails = []
                this.formData.details.push(sitem)
              })
            }
          })
          // let details = [...this.formData.details]
          // let newDetails = []
          // this.chosedArea.forEach((item) => {
          //   let index = -1
          //   details.forEach((sitem, sindex) => {
          //     if (item.name.indexOf(sitem.deliveryAddrName) > -1) {
          //       index = sindex
          //     }
          //   })
          //   if (index == -1) {
          //     this.formData.details.push({
          //       continuedPrice: 0,
          //       continuedUnit: 1,
          //       deliveryAddrCode: item.value,
          //       deliveryAddrName: item.realname,
          //       freightWay: 0,
          //       price: 0,
          //       startUnit: 1
          //     })
          //   } else {
          //     this.formData.details.push({
          //       continuedPrice: details[index].continuedPrice,
          //       continuedUnit: details[index].continuedUnit,
          //       deliveryAddrCode: details[index].value,
          //       deliveryAddrName: details[index].realname,
          //       // freightWay: details[index].freightWay,
          //       freightWay: this.formData.calcuType,
          //       price: details[index].price,
          //       startUnit: details[index].startUnit
          //     })
          //   }
          // })
          if (this.id) {
            this.formData.id = this.id
          }
          this.centerDialogVisible2 = true
          return
        } else {
          return false
        }
      })
    },
    // 确定提交
    sureSave() {
      this.btnLoading = true
      addAndUpdate(this.formData).then(res => {
        if (res.code == 0) {
          let text = '新建成功'
          if (this.id) {
            text = '编辑成功'
          }
          this.$message({
            type: 'success',
            message: text,
            duration: 1000,
            onClose: () => {
              this.centerDialogVisible2 = false
              this.updateStatus()
              // this.$store.dispatch('delVisitedViews', this.$route);
              // this.$router.push({
              //   name: 'feightlist'
              // })
            }
          })
        }
        this.btnLoading = false
      }).catch(err => {
        this.btnLoading = false
        this.$message({
          type: 'error',
          message: '发生错误'
        })
      })
    },
    updateStatus() {
      this.$store.dispatch('delVisitedViews', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>
<style>
.conf-wrapper .tip {
  padding: 20px 0;
  text-align: center;
  font-size: 16px;
}

.mfreight-title {
  padding: 20px;
  background-color: #eeeeee;
  margin-bottom: 20px;
}
.mfreight-area .el-form .el-input {
  width: auto;
}
.cell .area-wrapper {
  display: flex;
  align-items: center;
}
.commodity-mfreight-edit .area-wrapper {
    overflow: hidden;
    vertical-align: top;
    font-size: 0;
}
.commodity-mfreight-edit .area-list {
    text-align: left;
    display: inline-block;
    width: 80%;
    border-right: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
    font-size: 14px;
}
.commodity-mfreight-edit .area-edit {
    vertical-align: middle;
    font-size: 14px;
  width: 20%;
  text-align: center;
  justify-content: center;
}
.mfreight-area {
    padding: 0 40px;
}
.commodity-mfreight-edit .area-title-wrapper {
    padding-bottom: 20px;
    width: 90%;
}
.commodity-mfreight-edit .title-free {
    font-size: 16px;
    float: left;
    line-height: 30px;
}
.commodity-mfreight-edit .area-btn {
  float: right;
  margin-right: 10px;
  margin-left: 0px;
}
</style>
